package jiaxa.com.jsbridge.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.File;

/**
 * Created by jiaxa on 2017/12/8.
 */

public class ImageUtil {

    public static  String imageToBase64(Bitmap bitmap){
        ByteArrayOutputStream stream=new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG,100,stream);  //参数如果为100那么就不压缩
        byte[] bytes=stream.toByteArray();
        String base64= Base64.encodeToString(bytes,Base64.DEFAULT);
        return base64;
    }

    public static  String imageToBase64(String path){
        if (TextUtils.isEmpty(path)){
            return "";
        }
        File file=new File(path);
        if (!file.exists()){
            return "";
        }
        Bitmap bitmap= BitmapFactory.decodeFile(path);
        String base64= imageToBase64(bitmap);
        return base64;
    }

    public  static Bitmap  base64ToBitmap(String base64String)
    {
        byte[] bitmapArray = Base64.decode(base64String, Base64.DEFAULT);
        Bitmap bitmap=BitmapFactory.decodeByteArray(bitmapArray,0,bitmapArray.length);
        return bitmap;
    }

}
